package tools

import (
	"math"
	"math/rand"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

var (
	BaseString = "Ds3K9ZNvWmHcakr1oPnxh4qpMEzAye8wX5IdJ2LFujUgtC07lOTb6GYBQViSfR"
	BaseStringLength = uint64(len(BaseString))
)
//获取URL中批量id并解析
func IdsStrToIdsIntGroup(key string, c *gin.Context) []int {
	return IdsStrToIdsIntGroupStr(c.Param(key))
}

type Ids struct {
	Ids []int
}

func IdsStrToIdsIntGroupStr(keys string) []int {
	IDS := make([]int, 0)
	ids := strings.Split(keys, ",")
	for i := 0; i < len(ids); i++ {
		ID, _ := StringToInt(ids[i])
		IDS = append(IDS, ID)
	}
	return IDS
}

func Int2String(l int) string {
	str := "bdMWkcQ75Ta3P2jIorXSGEv4NtDUmqzRVgCep8HKwu0ixfJB61hLn9FAsZyYlO"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

//// Int2String converts an unsigned 64bit integer to a string.
//func Int2String(seq uint64) (shortURL string) {
//	charSeq := []rune{}
//	if seq != 0 {
//		for seq != 0 {
//			mod := seq % BaseStringLength
//			div := seq / BaseStringLength
//			charSeq = append(charSeq, rune(BaseString[mod]))
//			seq = div
//		}
//	} else {
//		charSeq = append(charSeq, rune(BaseString[seq]))
//	}
//
//	tmpShortURL := string(charSeq)
//	shortURL = reverse(tmpShortURL)
//	return
//}

// String2Int converts a short URL string to an unsigned 64bit integer.
func String2Int(shortURL string) (seq uint64) {
	shortURL = reverse(shortURL)
	for index, char := range shortURL {
		base := uint64(math.Pow(float64(BaseStringLength), float64(index)))
		seq += uint64(strings.Index(BaseString, string(char))) * base
	}
	return
}

func reverse(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}
